package com.zzyl.serve.service.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.druid.sql.visitor.SQLASTOutputVisitor;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.R;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.SecurityUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.common.utils.WechatUtil;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.serve.domain.DeviceData;
import com.zzyl.serve.domain.Elder;
import com.zzyl.serve.domain.FamilyMember;
import com.zzyl.serve.domain.member.FamilyMemberElder;
import com.zzyl.serve.dto.MemberLoginDto;
import com.zzyl.serve.dto.member.AddFamilyDto;
import com.zzyl.serve.dto.member.DeviceDataListDto;
import com.zzyl.serve.mapper.ElderMapper;
import com.zzyl.serve.mapper.FamilyMemberMapper;
import com.zzyl.serve.service.IFamilyMemberService;
import com.zzyl.serve.vo.FamilyElderVo;
import com.zzyl.serve.vo.member.DeviceDataListVo;
import com.zzyl.serve.vo.member.ElderDeviceInfoVo;
import com.zzyl.serve.vo.member.HealthDataVo;
import com.zzyl.serve.vo.MemberLoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Consumer;

/**
 * 老人家属Service业务层处理
 *
 * @author liuyp
 * @date 2025-08-21
 */
@Slf4j
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {
    @Autowired
    private FamilyMemberMapper familyMemberMapper;
    @Autowired
    private WechatUtil wechatUtil;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ElderMapper elderMapper;

    private static final List<String> nickNamePool = List.of("生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝");

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;


    /**
     * 查询老人家属
     *
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id) {
        return familyMemberMapper.selectById(id);
    }

    /**
     * 查询老人家属列表
     *
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember) {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember) {
        return familyMemberMapper.insert(familyMember);
    }

    /**
     * 修改老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember) {
        return familyMemberMapper.updateById(familyMember);
    }

    /**
     * 批量删除老人家属
     *
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids) {
        return familyMemberMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除老人家属信息
     *
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id) {
        return familyMemberMapper.deleteById(id);
    }

    @Override
    public MemberLoginVo login(MemberLoginDto dto) {
        // 1. 向微信平台发请求获取openid
        String openid = wechatUtil.getOpenid(dto.getCode());
        // 2. 向微信平台发请求获取手机号
        String phone = wechatUtil.getPhone(dto.getPhoneCode());
        // 3. 根据微信账号openid，到数据库表里查询一下
        LambdaQueryWrapper<FamilyMember> wrapper = Wrappers.<FamilyMember>lambdaQuery().eq(FamilyMember::getOpenId, openid);
        FamilyMember familyMember = familyMemberMapper.selectOne(wrapper);
        // 4. 判断是否查到家属信息了
        if (familyMember == null) {
            familyMember = new FamilyMember();
            // 给用户设置昵称，而不是使用了用户的微信昵称。昵称：从nickNamePool里随机取一个昵称，再拼接上手机号后4位
            familyMember.setName(nickNamePool.get(new Random().nextInt(nickNamePool.size())) + phone.substring(phone.length() - 4));
            familyMember.setOpenId(openid);
            familyMember.setPhone(phone);
            save(familyMember);
        } else {
            // 如果手机号 和 数据库里的手机号不同，则需要更新手机号
            if (!phone.equals(familyMember.getPhone())) {
                familyMember.setPhone(phone);
                updateById(familyMember);
            }
        }
        // 5. 准备返回值
        MemberLoginVo vo = new MemberLoginVo();
        vo.setNickName(familyMember.getName());
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", familyMember.getId());
        claims.put("name", familyMember.getName());
        vo.setToken(tokenService.createToken(claims));
        return vo;
    }

    /**
     * 查询健康数据
     *
     * @param iotId
     * @return
     */
    @Override
    public List<HealthDataVo> queryServiceProperties(String iotId) {
        //获取华为云上报到redis中的数据， 客户端传入的iotId对比redis的iotId值是否一致,  一致就获取数据封装成响应数据   不一致报错抛异常，反馈前端
        //获取redis数据
        List<Object> redisdata = redisTemplate.opsForHash().values(CacheConstants.IOT_DEVICE_LAST_DATA);
        if (redisdata == null) {
            throw new RuntimeException("查询不到设备上传的数据，请重新上传数据");
        }
        List<HealthDataVo> vos = new ArrayList<>(); //返回的集合

        for (Object datalist : redisdata) {
            //json转换
            List<DeviceData> list = JSONUtil.toList(datalist.toString(), DeviceData.class);
            for (DeviceData deviceData : list) {
                if (deviceData.getIotId().equals(iotId)) {

                    HealthDataVo vo = new HealthDataVo(); //响应对象
                    vo.setFunctionId(deviceData.getFunctionId());
                    vo.setValue(deviceData.getDataValue());
                    vo.setEventTime(deviceData.getAlarmTime().toString());
                    vos.add(vo);
                } else {
                    throw new RuntimeException("设备ID不匹配,请检查老人是否绑定设备");
                }
            }
        }
        log.info("查询健康数据：{}", vos);
        return vos;
    }


}
